<!DOCTYPE html>
<html>
<head>
    <title>麦克风权限测试</title>
    <meta charset="utf-8">
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .test-section {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        .status {
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .success { background-color: #d4edda; color: #155724; }
        .error { background-color: #f8d7da; color: #721c24; }
        .warning { background-color: #fff3cd; color: #856404; }
        .info { background-color: #d1ecf1; color: #0c5460; }
        
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        button:hover:not(:disabled) {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <h1>🎤 Network RC 麦克风权限测试</h1>
    
    <div class="test-section">
        <h2>环境检查</h2>
        <div id="environment-status"></div>
    </div>
    
    <div class="test-section">
        <h2>权限状态</h2>
        <div id="permission-status"></div>
        <button id="check-permission">检查权限</button>
        <button id="request-permission">请求权限</button>
    </div>
    
    <div class="test-section">
        <h2>麦克风测试</h2>
        <div id="microphone-status"></div>
        <button id="test-microphone">测试麦克风</button>
        <button id="stop-test" disabled>停止测试</button>
    </div>
    
    <div class="test-section">
        <h2>解决方案</h2>
        <div id="solutions"></div>
    </div>

    <script>
        let stream = null;
        
        // 检查环境
        function checkEnvironment() {
            const statusDiv = document.getElementById('environment-status');
            let html = '';
            
            // 检查HTTPS
            const isHttps = window.location.protocol === 'https:';
            const isLocalhost = window.location.hostname === 'localhost' || 
                               window.location.hostname === '127.0.0.1';
            const isSecure = isHttps || isLocalhost;
            
            html += `<div class="status ${isSecure ? 'success' : 'warning'}">
                🔒 安全上下文: ${isSecure ? '✅ 安全' : '⚠️ 建议使用HTTPS或localhost'}
            </div>`;
            
            // 检查浏览器支持
            const hasGetUserMedia = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
            html += `<div class="status ${hasGetUserMedia ? 'success' : 'error'}">
                🌐 浏览器支持: ${hasGetUserMedia ? '✅ 支持' : '❌ 不支持'}
            </div>`;
            
            // 显示浏览器信息
            const userAgent = navigator.userAgent;
            let browser = '未知';
            if (userAgent.includes('Chrome')) browser = 'Chrome';
            else if (userAgent.includes('Firefox')) browser = 'Firefox';
            else if (userAgent.includes('Safari')) browser = 'Safari';
            else if (userAgent.includes('Edge')) browser = 'Edge';
            
            html += `<div class="status info">
                📱 浏览器: ${browser} | 协议: ${window.location.protocol}
            </div>`;
            
            statusDiv.innerHTML = html;
        }
        
        // 检查权限状态
        async function checkPermissionStatus() {
            const statusDiv = document.getElementById('permission-status');
            
            try {
                if (!navigator.permissions) {
                    statusDiv.innerHTML = '<div class="status warning">⚠️ 浏览器不支持权限查询API</div>';
                    return;
                }
                
                const permission = await navigator.permissions.query({ name: 'microphone' });
                let statusClass = 'info';
                let icon = '❓';
                let text = '未知';
                
                switch (permission.state) {
                    case 'granted':
                        statusClass = 'success';
                        icon = '✅';
                        text = '已授权';
                        break;
                    case 'denied':
                        statusClass = 'error';
                        icon = '❌';
                        text = '已拒绝';
                        break;
                    case 'prompt':
                        statusClass = 'warning';
                        icon = '🔔';
                        text = '需要请求权限';
                        break;
                }
                
                statusDiv.innerHTML = `<div class="status ${statusClass}">
                    ${icon} 麦克风权限: ${text}
                </div>`;
                
                // 监听权限变化
                permission.onchange = () => checkPermissionStatus();
                
            } catch (error) {
                statusDiv.innerHTML = `<div class="status error">❌ 权限检查失败: ${error.message}</div>`;
            }
        }
        
        // 请求麦克风权限
        async function requestPermission() {
            const statusDiv = document.getElementById('microphone-status');
            
            try {
                statusDiv.innerHTML = '<div class="status info">🎤 正在请求麦克风权限...</div>';
                
                const testStream = await navigator.mediaDevices.getUserMedia({ audio: true });
                
                // 立即停止流
                testStream.getTracks().forEach(track => track.stop());
                
                statusDiv.innerHTML = '<div class="status success">✅ 麦克风权限已获得！</div>';
                checkPermissionStatus();
                
            } catch (error) {
                let errorMsg = '权限请求失败';
                let solution = '';
                
                switch (error.name) {
                    case 'NotAllowedError':
                        errorMsg = '麦克风权限被拒绝';
                        solution = '请点击地址栏的锁头图标，允许访问麦克风';
                        break;
                    case 'NotFoundError':
                        errorMsg = '未找到麦克风设备';
                        solution = '请检查麦克风是否正确连接';
                        break;
                    case 'NotSupportedError':
                        errorMsg = '浏览器不支持麦克风功能';
                        solution = '请更新浏览器或使用现代浏览器';
                        break;
                    case 'SecurityError':
                        errorMsg = '安全限制';
                        solution = '请使用HTTPS协议或localhost访问';
                        break;
                    default:
                        errorMsg = error.message;
                }
                
                statusDiv.innerHTML = `
                    <div class="status error">❌ ${errorMsg}</div>
                    ${solution ? `<div class="status warning">💡 ${solution}</div>` : ''}
                `;
                
                updateSolutions(error.name);
            }
        }
        
        // 测试麦克风
        async function testMicrophone() {
            const statusDiv = document.getElementById('microphone-status');
            
            try {
                statusDiv.innerHTML = '<div class="status info">🎤 启动麦克风测试...</div>';
                
                stream = await navigator.mediaDevices.getUserMedia({ 
                    audio: {
                        sampleRate: 16000,
                        channelCount: 1,
                        echoCancellation: true,
                        noiseSuppression: true
                    }
                });
                
                // 创建音频上下文来检测音量
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const source = audioContext.createMediaStreamSource(stream);
                const analyser = audioContext.createAnalyser();
                source.connect(analyser);
                
                analyser.fftSize = 256;
                const dataArray = new Uint8Array(analyser.frequencyBinCount);
                
                function updateVolume() {
                    analyser.getByteFrequencyData(dataArray);
                    const average = dataArray.reduce((a, b) => a + b) / dataArray.length;
                    const volume = Math.round((average / 255) * 100);
                    
                    statusDiv.innerHTML = `
                        <div class="status success">
                            ✅ 麦克风工作正常！音量: ${volume}%
                            <div style="width: 100%; background: #f0f0f0; height: 10px; margin: 5px 0;">
                                <div style="width: ${volume}%; background: #28a745; height: 100%;"></div>
                            </div>
                        </div>
                    `;
                    
                    if (stream) {
                        requestAnimationFrame(updateVolume);
                    }
                }
                
                updateVolume();
                
                document.getElementById('test-microphone').disabled = true;
                document.getElementById('stop-test').disabled = false;
                
            } catch (error) {
                statusDiv.innerHTML = `<div class="status error">❌ 麦克风测试失败: ${error.message}</div>`;
            }
        }
        
        // 停止测试
        function stopTest() {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
                stream = null;
                
                document.getElementById('microphone-status').innerHTML = 
                    '<div class="status info">🛑 麦克风测试已停止</div>';
                
                document.getElementById('test-microphone').disabled = false;
                document.getElementById('stop-test').disabled = true;
            }
        }
        
        // 更新解决方案
        function updateSolutions(errorType) {
            const solutionsDiv = document.getElementById('solutions');
            let solutions = '';
            
            switch (errorType) {
                case 'NotAllowedError':
                    solutions = `
                        <h3>🔧 权限被拒绝的解决方案：</h3>
                        <ol>
                            <li>点击地址栏左侧的🔒锁头图标</li>
                            <li>在弹出菜单中找到"麦克风"选项</li>
                            <li>将权限设置为"允许"</li>
                            <li>刷新页面重新测试</li>
                        </ol>
                    `;
                    break;
                case 'SecurityError':
                    solutions = `
                        <h3>🛡️ 安全限制的解决方案：</h3>
                        <ol>
                            <li>使用HTTPS协议访问：<code>https://your-domain.com</code></li>
                            <li>或者在本地访问：<code>http://localhost:8080</code></li>
                            <li>确保网站证书有效（如使用HTTPS）</li>
                        </ol>
                    `;
                    break;
                default:
                    solutions = `
                        <h3>🔧 通用解决方案：</h3>
                        <ol>
                            <li>检查麦克风设备是否正常工作</li>
                            <li>确保没有其他应用占用麦克风</li>
                            <li>尝试重启浏览器</li>
                            <li>检查系统音频权限设置</li>
                            <li>使用现代浏览器（Chrome、Edge、Firefox等）</li>
                        </ol>
                    `;
            }
            
            solutionsDiv.innerHTML = solutions;
        }
        
        // 初始化
        window.onload = function() {
            checkEnvironment();
            checkPermissionStatus();
            
            document.getElementById('check-permission').onclick = checkPermissionStatus;
            document.getElementById('request-permission').onclick = requestPermission;
            document.getElementById('test-microphone').onclick = testMicrophone;
            document.getElementById('stop-test').onclick = stopTest;
            
            // 页面卸载时清理资源
            window.onbeforeunload = function() {
                if (stream) {
                    stream.getTracks().forEach(track => track.stop());
                }
            };
        };
    </script>
</body>
</html>